package middlewareLogExtraction.model;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogEntry {
	private final String logEntryPattern = "([-.\\d]+)\\s+([^\\s]+ui)\\s+\\[(\\d+)\\]\\s+(.*)";
	private final String timeStempPattern = "(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2}).(\\d{2}).(\\d{2}).(\\d{6})";

	private Date timeStamp;
	private String middelWareId;
	private String nestingLevel;
	private String text;
	private RegexHelper regexHelper;

	public LogEntry(String line, RegexHelper regexHelper) {
		this.regexHelper = regexHelper;
		parseLogLine(line);
	}

	private void parseLogLine(String line) {
		Matcher matcher = regexHelper.regexFind(line, logEntryPattern);
		if (matcher != null) {
			this.timeStamp = parseTime(matcher.group(1));
			this.middelWareId = matcher.group(2);
			this.nestingLevel = matcher.group(3);
			this.text = matcher.group(4);
		}
	}

	private Date parseTime(String timeText) {
		Matcher matcher = regexHelper.regexFind(timeText, timeStempPattern);
		if (matcher != null) {
			Date date = new Date();
			date.setYear(new Integer(matcher.group(1)).intValue());
			date.setMonth(new Integer(matcher.group(2)).intValue());
			date.setDate(new Integer(matcher.group(3)).intValue());
			date.setHours(new Integer(matcher.group(4)).intValue());
			date.setMinutes(new Integer(matcher.group(5)).intValue());
			date.setSeconds(new Integer(matcher.group(6)).intValue());

			return date;
		}
		return null;
	}

	public Date getTimeStamp() {
		return this.timeStamp;
	}

	public String getMiddelWareId() {
		return middelWareId;
	}

	public String getNestingLevel() {
		return nestingLevel;
	}

	public String getText() {
		return text;
	}

	public boolean isSpTimingEntry() {
		Record rec = RecordFactory.createRecord(this.text, this.regexHelper);
		if (rec instanceof SPTimingRecord) {
			return true;
		}
		return false;
	}

	public boolean isSpTimingEntryOfSp(String spName) {
		Record rec = RecordFactory.createRecord(this.text, this.regexHelper);
		if (rec instanceof SPTimingRecord) {
			if (rec.getElement(1).equals(spName))
				return true;
		}
		return false;
	}

	public boolean isLoginEntryOfUser(String name) {
		Record rec = RecordFactory.createRecord(this.text, this.regexHelper);
		if (rec instanceof LoginRecord) {
			if (rec.getElement(1).equals(name))
				return true;
		}
		return false;
	}

	public boolean isLoginEntry() {
		Record rec = RecordFactory.createRecord(this.text, this.regexHelper);
		if (rec instanceof LoginRecord) {
			return true;
		}
		return false;
	}

	public boolean isProductCreationEntry() {
		Record rec = RecordFactory.createRecord(this.text, this.regexHelper);
		if (rec instanceof ProductRecord)
			return true;
		return false;
	}

}
